package com.rzico.sbl.ui.manual

import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityCommonListBinding
import com.rzico.sbl.model.RecordFindData
import com.rzico.sbl.other.NormalCallDecoration
import com.rzico.sbl.other.userRole
import com.rzico.sbl.ui.member.MemberAdressEditActivity
import com.rzico.sbl.viewmodel.ManualViewModel
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.find
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.getExtra
import com.xinnuo.common.extend.gone
import com.xinnuo.common.extend.goneValue
import com.xinnuo.common.extend.ifNotEmpty
import com.xinnuo.common.extend.inflate
import com.xinnuo.common.extend.notEmpty
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.extend.visibleValue
import com.xinnuo.common.helper.dp2px
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.utils.setColor
import com.xinnuo.slimadapter.SlimAdapter
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class ManualMobileActivity : BaseActivity(R.layout.activity_common_list) {

    private val mBinding by lazy { ActivityCommonListBinding.bind(getRootView()) }

    private lateinit var mMobile: String
    private lateinit var mMemberId: String

    override fun getViewModel() = get<ManualViewModel>()

    override fun initData() {
        initTitle("接单详情")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关会员信息\n点击去添加会员吧！"
                }

                recycleList.also { view ->
                    view.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData() }
                    )

                    view.addItemDecoration(
                        object : NormalCallDecoration() {
                            override fun getHeaderName(index: Int): String {
                                val item = mList[index] as RecordFindData
                                return item.memberMobile
                            }
                        }.apply {
                            setFooterHeight(dp2px(13f))

                            setOnDecorationHeadDraw { index ->
                                val item = mList[index] as RecordFindData

                                val innerView = inflate<View>(R.layout.header_manual_mobile)
                                innerView.find<TextView>(R.id.header_title)
                                    .setColor(
                                        "${item.memberName}${item.memberMobile.ifNotEmpty { " - $it" }}",
                                        mMobile,
                                        "#FF0000"
                                    )
                                innerView.find<TextView>(R.id.header_hint)
                                    .isInvisible = userRole !in "1,2"
                                innerView.find<ImageView>(R.id.header_arrow)
                                    .isInvisible = userRole !in "1,2"

                                return@setOnDecorationHeadDraw innerView
                            }

                            setOnHeaderClickListener {
                                val item = mList[it] as RecordFindData

                                (userRole in "1,2")
                                    .condition {
                                        startActivityEx<MemberAdressEditActivity>(
                                            "memberId" to item.memberId,
                                            "memberPhone" to mMobile
                                        )
                                    }
                            }
                        }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<RecordFindData>(R.layout.item_manual_list) { jector, bean, _ ->
                            jector.apply {
                                gone(R.id.item_manual_owe)
                                text(R.id.item_manual_card, "NO.${bean.cardNo}")
                                text(R.id.item_manual_name, bean.consignee)
                                text(R.id.item_manual_adress, bean.address)

                                visibility(
                                    R.id.item_manual,
                                    goneValue { bean.id.isNullOrEmpty() }
                                )

                                visibility(
                                    R.id.item_manual_def,
                                    visibleValue { bean.default ?: false }
                                )

                                with<ImageView>(R.id.item_manual_logo) {
                                    it.loadCircleImage(bean.logo, R.mipmap.default_user)
                                }

                                with<TextView>(R.id.item_manual_phone) {
                                    it.setColor(
                                        bean.phone.orEmpty(),
                                        mMobile,
                                        "#FF0000"
                                    )
                                }

                                clicked {
                                    startActivityEx<ManualEditActivity>(
                                        "receiverId" to bean.id,
                                        "cardId" to bean.cardId,
                                        "memberId" to bean.memberId,
                                        "consignee" to bean.consignee,
                                        "phone" to bean.phone,
                                        "address" to bean.address
                                    )
                                }
                            }
                        }
                        .attachTo(view)
                }
            }
    }

    override fun initListener() {
        mMobile = intent.getExtra("mobile")
        mMemberId = intent.getExtra("memberId")

        mBinding.apply {
            listLayout
                .emptyLayout
                .emptyHint
                .oneClick {
                    startActivityEx<MemberAdressEditActivity>(
                        "memberPhone" to mMobile
                    )
                }
        }

        observe<String>("memberList") { updateList() }
        observe<String>("addressList") { updateList() }
    }

    /**
     * 会员收货地址列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .findMobile(
                phone = mMobile,
                onSuccess = {
                    mList.apply {
                        clear()
                        addItems(it)
                    }

                    mAdapter.setDataList(mList)

                    when {
                        mList.isEmpty() -> {
                            showToast("您还没有添加该会员！")

                            lifecycleScope.launch {
                                delay(300)

                                startActivityEx<MemberAdressEditActivity>(
                                    "memberPhone" to mMobile
                                )
                            }
                        }

                        mList.none {
                            it as RecordFindData
                            it.id != null && it.id!!.isNotEmpty()
                        } -> {
                            showToast("该会员还未添加地址！")

                            lifecycleScope.launch {
                                delay(300)

                                startActivityEx<MemberAdressEditActivity>(
                                    "memberId" to (mList[0] as RecordFindData).memberId,
                                    "memberPhone" to mMobile
                                )
                            }
                        }
                    }


                },
                onFinally = {
                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData()
    }

}